package com.xingda.packing.dmds.task.handle;


import com.xingda.packing.dmds.domain.PackProductionLine;
import com.xingda.packing.dmds.domain.ProductBoxLocation;
import com.xingda.packing.dmds.domain.Wheel;
import com.xingda.packing.dmds.enums.TaskState;
import com.xingda.packing.dmds.enums.TaskType;
import com.xingda.packing.dmds.task.ticket.CachePackingTicket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


@Slf4j
@Component("CachePackingDMDSHandle")
public class CachePackingHandle implements TaskHandleService {
    @Override
    public boolean accept(PackProductionLine productionLine, int area) {
        return checkTask(productionLine.getRobot().getTaskTicket(area), TaskType.CACHE_PALLETIZING);
    }

    @Override
    public void process(PackProductionLine productionLine, int area) {
        CachePackingTicket ticket = (CachePackingTicket) productionLine.getRobot().getTaskTicket(area);
        for (ProductBoxLocation productBoxLocation : productionLine.getProductArea().getLocationList(area)) {
            if (productBoxLocation.getLocationNo() == ticket.getProductBoxLocationNo()) {
                if (!productBoxLocation.isPhotoFinish() || productBoxLocation.isPalletComing()) {
                    productionLine.getRobot().createAlarmEvent("任务进行中托盘已拿走,请人工处理当前未完成任务", area);
                    ticket.setState(TaskState.FINISH);
                    productionLine.setInitRunning(area, false);
                    productionLine.getRobot().setTaskTicket(ticket, area);
                    productionLine.getRobot().clear(area);
                    return;
                }
            }
        }
        if (productionLine.getRobot().canAssignTask(area)) {
            log.info("开始执行缓存位到装箱位-handle-区域{}", area);
            Wheel wheel = ticket.getWheel();
            StringBuilder wheeNoSb = new StringBuilder();
            wheeNoSb.append(wheel.getAb()).append(wheel.getBarCode());
            if (wheeNoSb.length() == 14) {
                wheeNoSb.append("###");
            }
            productionLine.getRobot().startCacheGrab(ticket.getCacheLocationNo(), ticket.getProductBoxLocationNo(), ticket.getProductType(), wheeNoSb.toString(), area);
            log.info("区域{}->从缓存位码垛任务下发成功：缓存位抓取位置：{}，码垛托盘号：{},扭转值：{}", area, ticket.getCacheLocationNo(), ticket.getProductBoxLocationNo(), ticket.getWheel().getTorsionValue());
            ticket.setState(TaskState.RUNING);
            //事件记录
            productionLine.getRobot().handleCachePackingEvent(ticket, area);
            log.info("执行完成缓存位到装箱位-handle-区域{}", area);
        }
    }
}
